<script setup>
import { ref, onMounted, reactive } from 'vue';
import { fetchListWithChildren } from '@/api/productCate.js';
import { fetchBrandList } from '@/api/brand.js';
import { ElMessage } from 'element-plus';
import { useRoute } from 'vue-router';
import {getProduct} from "@/api/product.js";

const route = useRoute();

const brandListOptions = ref([]);
const productCateOptions = ref([]);
const selectProductCateValue = ref([]);
const productInfoForm = ref(null);

// 定义 form 并绑定到父组件传递的 product-param
const form = reactive({
  productCategoryId: '',
  name: '',
  subTitle: '',
  brandId: '',
  description: '',
  productSn: '',
  price: 0,
  originalPrice: 0,
  stock: 0,
  unit: '',
  weight: 0,
  sort: 0
});

// 定义验证规则
const rules = {
  productCategoryId: [{ required: true, message: '请选择商品分类', trigger: 'blur' }],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
  ],
  subTitle: [{ required: true, message: '请输入商品副标题', trigger: 'blur' }],
  brandId: [{ required: true, message: '请选择商品品牌', trigger: 'blur' }],
};

// 定义 emits 并接收父组件的 nextStep 方法
const emit = defineEmits(['nextStep']);

// 定义 handleNext 按钮方法
const handleNext1 = () => {
  // 验证表单
  productInfoForm.value.validate(valid => {
    if (valid) {
      // 将 form 数据赋值给父组件的 product-param
      Object.assign(props.productParam, form);
      emit('nextStep');
    } else {
      ElMessage.error('验证失败');
      return false;
    }
  });
};

// 定义 props 并接收父组件传递的 product-param
const props = defineProps({
  productParam: {
    type: Object,
    required: true
  },
  isEdit: {
    type: Boolean,
  }
});

onMounted(() => {
  if (!route.query.id) {
    console.log(props.isEdit);
    Object.assign(form, props.productParam);
    selectProductCateValue.value = [props.productParam.productCategoryId];
  } else {
    getProduct(route.query.id).then(res => {
      console.log(res.data.data);
      Object.assign(form, res.data.data);
      selectProductCateValue.value = res.data.data.productCategoryId;
    }).catch(err => {
      console.error(err);
      ElMessage.error('获取商品信息失败');
    });
  }
  getBrandList();
  getProductCateList();
});

// 获取商品分类数据
const getProductCateList = async () => {
  try {
    const res = await fetchListWithChildren();
    const result = res.data.data;
    productCateOptions.value = result.map(category => ({
      label: category.name,
      value: category.id,
      children: category.children ? category.children.map(child => ({
        label: child.name,
        value: child.id
      })) : []
    }));
  } catch (error) {
    console.error('获取商品分类失败:', error);
    ElMessage.error('获取商品分类失败');
  }
};

// 获取品牌数据
const getBrandList = async () => {
  try {
    const res = await fetchBrandList({
      pageSize: 100,
      pageNum: 1,
    });
    brandListOptions.value = res.data.data.list.map(brand => ({
      label: brand.name,
      value: brand.id
    }));
  } catch (error) {
    console.error('获取品牌信息失败:', error);
    ElMessage.error('获取品牌信息失败');
  }
};

// 处理商品分类变化
const handleChangeProductCate = (value) => {
  form.productCategoryId = value[value.length - 1];
};
</script>

<template>
  <div style="margin-top: 50px;">
    <el-form :model="form" :rules="rules" ref="productInfoForm" label-width="120px" label-position="right">
      <el-form-item label="商品分类:"  prop="productCategoryId">
        <el-cascader
            clearable
            v-model="selectProductCateValue"
            :options="productCateOptions"
            placeholder="请选择商品分类"
            @change="handleChangeProductCate"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="商品名称:" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品名称"  clearable></el-input>
      </el-form-item>
      <el-form-item label="副标题:" prop="subTitle">
        <el-input v-model="form.subTitle" placeholder="请输入商品副标题" clearable></el-input>
      </el-form-item>
      <el-form-item label="商品品牌:" clearable prop="brandId">
        <el-select v-model="form.brandId" placeholder="请选择商品品牌" clearable>
          <el-option
              v-for="brand in brandListOptions"
              :key="brand.value"
              :label="brand.label"
              :value="brand.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品介绍:">
        <el-input
            :autoSize="true"
            v-model="form.description"
            clearable
            placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item label="商品货号:">
        <el-input v-model="form.productSn" placeholder="请输入商品货号" clearable></el-input>
      </el-form-item>
      <el-form-item label="商品售价:">
        <el-input v-model="form.price" type="number"></el-input>
      </el-form-item>
      <el-form-item label="市场价格:">
        <el-input v-model="form.originalPrice" type="number"></el-input>
      </el-form-item>
      <el-form-item label="商品库存:">
        <el-input v-model="form.stock" type="number"></el-input>
      </el-form-item>

      <el-form-item label="计量单位:">
        <el-input v-model="form.unit" clearable></el-input>
      </el-form-item>
      <el-form-item label="商品重量:">
        <el-input v-model="form.weight" style="width: 400px" type="number"></el-input>
        <span style="margin-left: 20px">克</span>
      </el-form-item>
      <el-form-item label="商品排序:">
        <el-input v-model="form.sort" type="number"></el-input>
      </el-form-item>
      <el-form-item style="text-align: center">
        <el-button type="primary" @click="handleNext1">下一步，填写商品促销</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>

</style>
